package qeug.shsh.task;

import cn.hutool.Hutool;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import kd.bos.context.RequestContext;
import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.operate.result.IOperateInfo;
import kd.bos.entity.operate.result.OperateErrorInfo;
import kd.bos.entity.operate.result.OperationResult;
import kd.bos.exception.KDException;
import kd.bos.orm.ORM;
import kd.bos.orm.query.QFilter;
import kd.bos.schedule.executor.AbstractTask;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.operation.OperationServiceHelper;
import org.springframework.util.Base64Utils;
import qeug.shsh.helper.FacadeHelper;

import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @projectName: qeug-cosmic-root-project
 * @package: qeug.shsh.opplugin
 * @className: CostCenterTask
 * @author: wenyx
 * @description: TODO
 * @date: 2024/1/5 16:41
 * @version: 1.0
 */
public class CostCenterTask extends AbstractTask {
    @Override
    public void execute(RequestContext requestContext, Map<String, Object> map) throws KDException {
        ORM orm = ORM.create();
        String sap_url = System.getProperty("cost.url");
        String basicAuthUserName = System.getProperty("po.user");
        String basicAuthPassword = System.getProperty("po.password");

        String basic = basicAuthUserName + ":" + basicAuthPassword;
        String encoding = Base64Utils.encodeToString(basic.getBytes(StandardCharsets.UTF_8));
        String json = HttpRequest.post(sap_url)
                .header("Authorization", "Basic " + encoding)
                .body("{}")
                .execute().body();
        JSONObject jsonObject = JSONObject.parseObject(json);
        JSONArray items = jsonObject.getJSONArray("items");
        DynamicObjectCollection dynamicObjects = new DynamicObjectCollection();
        for (int  i=0;i<items.size();i++) {
            JSONObject jsInfo = items.getJSONObject(i);
            String number = jsInfo.getString("KOSTL");//编码
            String name = jsInfo.getString("MCTXT");//名称
            String company = jsInfo.getString("BUKRS");//公司
            Date starTime = jsInfo.getDate("DATAB");//开始时间
            Date endtime = jsInfo.getDate("DATBI");//结束时间
            String type = jsInfo.getString("KOSAR");//类型
            String gnfw = jsInfo.getString("FKBER");//功能范围
            DynamicObject eixcostcenter = BusinessDataServiceHelper.loadSingle("bos_costcenter", new QFilter("number", "=", number).toArray());
            DynamicObject costcenter = orm.newDynamicObject("bos_costcenter");
            if(eixcostcenter!=null){
                 costcenter = eixcostcenter;
            }

            DynamicObject org = BusinessDataServiceHelper.loadSingle("bos_org", new QFilter("number", "=", company).toArray());
            costcenter.set("number",number);
            costcenter.set("name",name);
            costcenter.set("company",org);
            costcenter.set("qeug_reasoncode",gnfw);
            if (type.equals("L")){
                type="1";
            } else if (type.equals("V")) {
                type="3";
            }
            DynamicObject orgduty = BusinessDataServiceHelper.loadSingle("bos_org_duty", new QFilter("number", "=", type).toArray());
            costcenter.set("orgduty",orgduty);
            if (isCurrentDateBetween(starTime, endtime)) {
                dynamicObjects.add(costcenter);
            }
        }
        StringBuilder stringBuilder = new StringBuilder();
        OperationResult result = OperationServiceHelper.executeOperate("save", "bos_costcenter",dynamicObjects.toArray());
        List<IOperateInfo> errorInfos = result.getAllErrorOrValidateInfo();
        int size = errorInfos.size() + result.getSuccessPkIds().size();
        if (size > 1) {
            int i = 0;
            for(int len = errorInfos.size(); i < 5 && i < len; ++i) {
                stringBuilder.append((errorInfos.get(i)).getMessage());
            }
            stringBuilder.toString();
        } else if (!errorInfos.isEmpty()) {
            OperateErrorInfo errorInfo = (OperateErrorInfo)errorInfos.get(0);
            stringBuilder.append(errorInfo.getMessage() == null ? "" : errorInfo.getMessage());
        } else{
            stringBuilder.append(result.getMessage() == null ? "" : result.getMessage());
        }
        HashMap<String, Object> log = new HashMap<>();
        log.put("operationModule", "获取sap成本中心");
        log.put("url", sap_url);
        log.put("user", basicAuthUserName);
        log.put("mode", "POST");
        log.put("action", "");
        log.put("opdate", new Date());
        log.put("mainstring", stringBuilder.toString());
        log.put("responsebody", json);
        log.put("operating_mode", "");
        FacadeHelper.apiLog(log);
    }


    public static boolean isCurrentDateBetween(Date startDate, Date endDate) {
        Date currentDate = new Date();
        return (currentDate.after(startDate) || currentDate.equals(startDate)) &&
                (currentDate.before(endDate) || currentDate.equals(endDate));
    }
}
